import { useNavigate, useParams } from "react-router-dom";
import Search from "antd/es/input/Search";
import './SubCategoryProduct.css'
import { Button, List, Statistic, Tag } from "antd";
import { LeftOutlined } from "@ant-design/icons";
import React, { useEffect, useState } from "react";
import { getProductList } from "../../services/product";

const SubCategoryProduct = () => {
    const { id } = useParams();
    const navigate = useNavigate();

    const [productList, setProductList] = useState([]);
    const [subCategoryProducts, setSubCategoryProducts] = useState([]);
    const [searchValue, setSearchValue] = useState('');
    const [filteredProducts, setFilteredProducts] = useState([]);

    useEffect(() => {
        const fetchProductList = () => {
            getProductList({ page: 1, pageSize: 10 }).then(response => {
                if (response && response.result) {
                    console.log('Product List:', response.result);
                    const filtered = response.result.filter(product => product.category === id);
                    setProductList(response.result);
                    setSubCategoryProducts(filtered);
                } else {
                    console.error('Error fetching product list: Invalid response');
                }
            }).catch(error => {
                console.error('Error fetching product list:', error);
            });
        };

        fetchProductList();
        const interval = setInterval(fetchProductList, 1000); // Fetch every 1 seconds
        return () => clearInterval(interval); // Clear interval on component unmount
    }, [id]);

    useEffect(() => {
        if (searchValue) {
            const filtered = productList.filter(product =>
                product.productName.includes(searchValue) && product.category === id
            );
            setFilteredProducts(filtered);
        } else {
            setFilteredProducts(subCategoryProducts);
        }
    }, [searchValue, subCategoryProducts, productList, id]);

    const onSearch = (value) => {
        setSearchValue(value);
    }

    const goBackToCategory = () => {
        navigate("/productCategory");
    };

    const goToProductDetails = (id) => {
        navigate(`/product/${id}`);
    };

    const dataSource = searchValue ? filteredProducts : subCategoryProducts;

    return (
        <div style={{ minHeight: '100vh', margin: 'auto', backgroundColor: '#fff' }}>
            <div>
                <Button
                    icon={<LeftOutlined style={{ width: "30px", height: "30px", color: "rgba(255, 153, 102, 0.76)" }} />}
                    style={{
                        marginTop: "25px",
                        marginLeft: "5%",
                        border: "none"
                    }}
                    onClick={goBackToCategory}
                />
                <Search placeholder="请输入商品名称关键字" onSearch={onSearch} enterButton
                        style={{
                            width: "70%",
                            marginTop: "25px",
                            marginLeft: "5%"
                        }}
                />
            </div>

            <List
                itemLayout="vertical"
                dataSource={dataSource}
                style={{
                    margin: "25px auto",
                    width: "90%",
                }}
                renderItem={(item, index) => (
                    <List.Item
                        onClick={() => { goToProductDetails(item.id) }}>
                        <List.Item.Meta
                            avatar={<img src={item.details[0]} alt={item.name} style={{ width: "110px", height: "110px" }} />}
                            title={item.productName}
                            description={item.description}
                        />
                        <div style={{ width: "60%", marginLeft: "170px", marginTop: "-60px", display: "flex", justifyContent: "flex-end", rowGap: "10px", alignItems: "center" }}>
                            {item.services && item.services.map(service => (
                                <Tag bordered={false} color="red" style={{ height: "10px", textAlign: "center", lineHeight: "10px" }}>
                                    {service}
                                </Tag>
                            ))}
                        </div>
                        <div style={{ height: "40px", display: "flex", justifyContent: "flex-end", alignItems: "center", marginTop: "10px" }}>
                            <Statistic value={'￥' + item.price} style={{ color: '#FB5B40', textAlign: "center" }} />
                            <span style={{ color: "grey", marginLeft: "5px", paddingTop: "5px", lineHeight: "40px", textAlign: "center" }}>已售出{item.sales}+</span>
                        </div>
                    </List.Item>
                )}
            />
        </div>
    );
};

export default SubCategoryProduct;
